import java.io.IOException;
import java.net.DatagramPacket;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

public class Receiver implements Runnable {

	private Router router;
	private HashMap<String, Neighbor> neighbors;

	public Receiver(Router router) {
		this.router = router;
		this.neighbors = new HashMap<String, Neighbor>();
		for (Integer key : this.router.getRouters().keySet()) {
			String address = this.router.getRouters().get(key).getAddress();
			String port = this.router.getRouters().get(key).getPort();
			int id = this.router.getRouters().get(key).getId();
			
			for (Neighbor neighbor : router.getNeighbors()) {
				if (neighbor.getId() == id) {
					this.neighbors.put(address + port, neighbor);
				}
			}
		}
	}

	@Override
	public void run() {
		while (true) {
			byte[] receiveData = new byte[603];

			DatagramPacket receivePacket = new DatagramPacket(receiveData,receiveData.length);
			router.addCounterReceived();
			try {
				router.getSocket().receive(receivePacket);
				String msg = new String(receivePacket.getData());
				router.processMessage(msg);
				router.processNAlive(msg);
			} catch (IOException e) {
			}

			router.verificaNAlive();
			
			try {
				TimeUnit.MILLISECONDS.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace(); 
				System.exit(1);
			}
		}
	}
}
